package cmd

import (
	"fmt"
	"log"
	"os"

	"gitee.com/ysfzf/zerox/cmd/common"
	"github.com/spf13/cobra"
)

var apiCmd = &cobra.Command{
	Use:   "api",
	Short: "根据yaml文件配置生成api文件",
	Run: func(cmd *cobra.Command, args []string) {
		cfg, _ := cmd.Flags().GetString("config")
		if cfg == "" {
			gdb, err := conndb()
			if nil != err {
				log.Fatal(err)
			}
			dbname := gdb.Migrator().CurrentDatabase()
			cfg = dbname + "_api.yaml"
		}
		force, _ := cmd.Flags().GetBool("force")

		generateApi(cfg, force)
	},
}

func init() {
	apiCmd.Flags().StringP("config", "c", "", "The configuration file")
	apiCmd.Flags().BoolP("force", "f", false, "Force overwrite of existing .api file")
	rootCmd.AddCommand(apiCmd)
}

func generateApi(configFile string, force bool) {
	var c = new(common.ProtoConfig)
	err := common.LoadConfig(configFile, c)
	if err != nil {
		log.Fatal(err)
	}

	_, err = os.Stat(c.OutFile)
	if err == nil && !force {
		return
	}
	api, err := c.GenerateApi()
	if err != nil {
		// debug.PrintStack()
		log.Fatal(err)
	}
	err = common.WriteFile(c.OutFile, api.String())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Done.")
}
